/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.uch.biblioteca.managedBeans;

import java.io.BufferedReader;
import java.io.FileReader;
import javax.faces.event.ActionEvent;
import net.uch.biblioteca.hibernateSpringDao.HSBibCatalogoDAO;
import net.uch.util.CommonDAO;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import net.uch.TablaSistema.managedBeans.File;
import org.richfaces.event.UploadEvent;
import org.richfaces.model.UploadItem;
import javax.faces.model.SelectItem;
import net.uch.biblioteca.hibernateSpringDao.HSBibCatalogoDetalleDAO;
import net.uch.biblioteca.hibernateSpringDao.HSBibEjemplarDAO;
import net.uch.biblioteca.mapping.BibCatalogo;
import net.uch.biblioteca.mapping.BibCatalogoDetalle;
import net.uch.biblioteca.mapping.BibEjemplar;
import net.uch.biblioteca.mapping.TbCatalogo;
import net.uch.util.CommonWeb;

/**
 *
 * @author Vasquez
 */
public class mbImportarDoc {

    private ArrayList<File> files = new ArrayList<File>();
    private int uploadsAvailable = 5;
    private boolean autoUpload = false;
    private boolean useFlash = false;
    private SelectItem[] cboCatCol;
    private String sCatCol;

    public int getSize () {
        if ( getFiles().size() > 0 ) {
            return getFiles().size();
        } else {
            return 0;
        }
    }

    public SelectItem[] getCboCatCol () {
        try {

            List lstCatCol = CommonDAO.getTbCatalogoDAO().seleccionarCatalogo( "004" );
            if ( lstCatCol.size() > 0 ) {
                cboCatCol = new SelectItem[ lstCatCol.size() + 1 ];
                cboCatCol[0] = new SelectItem( "0", "[Seleccione]" );
                for ( int i = 0; i < lstCatCol.size(); i++ ) {
                    cboCatCol[i + 1] = new SelectItem( ((TbCatalogo) lstCatCol.get( i )).getCatCodigoGrupo() + ((TbCatalogo) lstCatCol.get( i )).getCatCodigoElemento(), ((TbCatalogo) lstCatCol.get( i )).getCatDescripcionElemento() );
                }
            } else {
                cboCatCol = new SelectItem[ 1 ];
                cboCatCol[0] = new SelectItem( "0", "[Seleccione]" );
            }
        } catch ( Exception e ) {
            e.printStackTrace();
        }
        return cboCatCol;
    }

    public void setCboCatCol ( SelectItem[] cboCatCol ) {
        this.cboCatCol = cboCatCol;
    }

    public String getsCatCol () {
        return sCatCol;
    }

    public void setsCatCol ( String sCatCol ) {
        this.sCatCol = sCatCol;
    }

    public mbImportarDoc () {
    }

    public void paint ( OutputStream stream, Object object ) throws IOException {
        stream.write( getFiles().get( (Integer) object ).getData() );
    }

    private String replaces ( String cadena ) {
        return cadena.replace( " ", "_" ).replace( "á", "a" ).replace( "é", "e" ).replace( "í", "i" ).replace( "ó", "o" ).replace( "ú", "u" ).replace( "ñ", "n" );
    }

    private String replacesCatalogo ( String cadena ) {

        return cadena.replace( "µ", "á").replace( "‚", "é" ).replace( "¡", "í" ).replace( "¢", "ó" ).replace( "ú", "ú" ).replace( "ñ", "n" ).replace( "¤", "ñ" ).replace( "…", "á" ).replace( "•", "ó" ).replace( "Š", "" ).replace( "£", "ú" ).replace( "?", "é" );
    }
    private String[] separa ( String a ) {
        String[] b;

        int nro_lin = (((a.trim()).length()) / 12);
        b = new String[ nro_lin ];
        for ( int i = 0; i < nro_lin; i++ ) {
            b[i] = a.substring( 0, 12 );
            a = a.substring( 12 );
        }
        return b;
    }

    public void listener ( UploadEvent event ) throws Exception {

        BibCatalogo cat = new BibCatalogo();
        BibCatalogoDetalle catdet = new BibCatalogoDetalle();
        BibEjemplar eje = new BibEjemplar();

        HSBibCatalogoDetalleDAO daoCatDet = CommonDAO.getBibCatalogoDetalleDAO();
        HSBibEjemplarDAO daoEje = CommonDAO.getBibEjemplarDAO();

        String ColeccionTipo = CommonWeb.getParamFromUI( "form1:cboLecTip" );

        daoCatDet.eliminarCatalogoDetalle( ColeccionTipo );


        UploadItem item = event.getUploadItem();
        String nombreArchivo = "";
        File file = new File();
        try {
            file.setLength( item.getData().length );
        } catch ( Exception e ) {
            e.printStackTrace();
        }
        nombreArchivo = replaces( item.getFileName() );
        file.setName( nombreArchivo );
        System.out.println( "item " + item.getContentType() );
        file.setMime( item.getContentType() );
        file.setData( item.getData() );
        files.add( file );
        uploadsAvailable--;


        String linea;
        linea = new String( file.getData() );
        String buffer = "";
        String[] buffer3;
        String[] arrayCatalogo = linea.split( "" );
        String rot_reg = "";
        String direc = "";
        int cont = 0;
        String[] adirec;
        try {
            for ( int i = 0; i < 100; i++ ) { //RECORRO LOS DOCUMENTOS
                arrayCatalogo[i] = arrayCatalogo[i].replace( "\r", "" ).replace( "\n", "" );
                if ( !arrayCatalogo[i].isEmpty() ) {
                    cont++;

//                    System.out.println( " array 1: " + arrayCatalogo[i] );

                    buffer = arrayCatalogo[i];

                    buffer = buffer.replace( "\r", "" ).replace( "\n", "" );

                    buffer = replacesCatalogo( arrayCatalogo[i] );

                    String[] buffer2 = buffer.split( "" );

//                    for ( int j = 0; j < buffer2.length; j++ ) {
//
//                        buffer2[j] = buffer2[j].replace( "\r", "" ).replace( "\n", "" );
//
//                    }

                    buffer = buffer2[0].replace( "\r", "" ).replace( "\n", "" );

                    buffer3 = buffer.split( "" );
                    rot_reg = buffer3[0].substring( 0, 24 );
                    direc = buffer3[0].substring( 24 );

                    adirec = separa( direc );

                    for ( int w = 0; w < adirec.length; w++ ) {
                        adirec[w] = adirec[w].substring( 0, 3 );
                    }

                    for ( int p = 0; p < adirec.length; p++ ) {
//                        System.out.println( "Cat_id" + (i + 1) + " Marc: " + adirec[p] + " = " + buffer2[p + 1] );
                        if ( (buffer2[p + 1].trim().length()) > 0 ) {

                            // INSERTAR A bib_catalogo_detalle
                            catdet.setCatId( cont );
                            catdet.setMarCodi( adirec[p] );
                            catdet.setMarCont( buffer2[p + 1] );
                            catdet.setCatCol( ColeccionTipo );
                            catdet.setCatEje( null );

                            if ( "921".equals( adirec[p] ) || "931".equals( adirec[p] ) || "941".equals( adirec[p] ) || "951".equals( adirec[p] ) ) {

                                catdet.setCatEje( buffer2[p + 1] );

                                // agrega ejemplares 921-931-941-951 a bibejemplar
                                if ( daoEje.buscarEjemplar( buffer2[p + 1] ) == null ) {
                                    eje.setCatEje( buffer2[p + 1] );
                                    eje.setEjeEst( "0" );
                                    daoEje.guardarEjemplar( eje );
                                }

                            }
                            if ( "960".equals( adirec[p] ) ) {

                                buffer2[p + 1] = buffer2[p + 1].substring( 12, 20 );
                                catdet.setCatEje( buffer2[p + 1] );

                                //agrega ejemplar tipo 960 a ejemplar
                                if ( daoEje.buscarEjemplar( buffer2[p + 1] ) == null ) {
                                    eje.setCatEje( buffer2[p + 1] );
                                    eje.setEjeEst( "0" );
                                    daoEje.guardarEjemplar( eje );
                                }
                            }

                            daoCatDet.guardarCatalogoDetalle( catdet );

                        }
                    }
                }
            }
        } catch ( Exception ex ) {
            ex.printStackTrace();
            System.out.println( "EX : " + ex );
            System.out.println( "EX : " + ex.getMessage() );
        }
    }

    public String clearUploadData () {
        files.clear();
        setUploadsAvailable( 5 );
        return null;
    }

    public long getTimeStamp () {
        return System.currentTimeMillis();
    }

    public ArrayList<File> getFiles () {
        return files;
    }

    public void setFiles ( ArrayList<File> files ) {
        this.files = files;
    }

    public int getUploadsAvailable () {
        return uploadsAvailable;
    }

    public void setUploadsAvailable ( int uploadsAvailable ) {
        this.uploadsAvailable = uploadsAvailable;
    }

    public boolean isAutoUpload () {
        return autoUpload;
    }

    public void setAutoUpload ( boolean autoUpload ) {
        this.autoUpload = autoUpload;
    }

    public boolean isUseFlash () {
        return useFlash;
    }

    public void setUseFlash ( boolean useFlash ) {
        this.useFlash = useFlash;
    }

    public void ImportarDocumento ( ActionEvent event ) throws Exception {

        HSBibCatalogoDAO daoCat = CommonDAO.getBibCatalogoDAO();


        String cadenaCatalogo = "datos del .ISO";
        String[] arrayCatalogo = cadenaCatalogo.split( "" );
    }
}
